<template>
	<view class="mainbord">
		<!--  -->

		<scroll-view
			class="scroll"
			:scroll-top="scroll"
			:scroll-into-view="viewId"
			scroll-y="true"
			:style="{ height: windowHeight - 140 - keyboardHeight + 'px' }"
			@click="TouchMain"
		>
			<view v-for="(item, index) in messages" :key="item.timestamp">
				<view class="msg_time" v-if="isTimeshow(item.timestamp, lastTimestamp(index))">{{ formatMessageTime(item.timestamp) }}</view>
				<view v-if="messages.length > 0" class="item" :class="item.userTel === user.userTel ? 'push' : 'pull'" :id="`msgall-${item.timestamp}`">
					<image :src="item.nicPic ? item.nicPic.url || '/static/logoGroup.png' : '/static/logoGroup.png'" mode="aspectFill" class="pic" />
					<view class="" style="display: flex; flex-direction: column">
						<view class="content" v-if="item.messageType === 2">
							{{ item.content.text }}
						</view>
						<view class="content" v-if="item.messageType === 1" :id="`msg-${item.timestamp}`">
							<view class="progress-bar" :style="{ width: (item.content.duration < 6 ? 100 : item.content.duration * 10) + 'rpx' }" @click.stop="handonPlay(item)">
								{{ currentMsg === item.timestamp ? progressPercent.toFixed(0) + '%' : item.content.duration + '秒' }}
								<view v-if="currentMsg === item.timestamp" class="progress" :style="{ width: progressPercent + '%' }"></view>
							</view>
						</view>

						<view class="media" v-else-if="item.messageType === 3 && item.content && item.content.mediaPath">
							<view v-for="(pic, index) in item.content.mediaPath" :key="pic && pic.fileID ? pic.fileID : index">
								<image :src="pic && pic.url ? pic.url : ''" mode="widthFix" @click="preview(pic && pic.url ? pic.url : '')"></image>
							</view>
						</view>
						<view class="video-thumbnail" v-else-if="item.messageType === 6 && item.content && item.content.videoPath && item.content.videoPath.videoPic">
							<view class="image-container">
								<image class="video_v" :src="item.content.videoPath.videoPic.tempFileURL || ''" mode="aspectFill" />
								<!-- 播放按钮 -->
							</view>
						</view>
					</view>
					<view v-if="!item.isSended" class="unsend" @click="reSendMsg(item)">
						<view class="">未发送</view>
						<image src="/static/unsend.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</scroll-view>
		<customnavbar :user="targetUser" @reLoadmsgList="reLoadmsgList"></customnavbar>
	
		<progressBar></progressBar>
		<recordVioce class="recordVioce" @handleclose="recordVioceClose" @voice_msg="voice_msg" v-if="isSpeak"></recordVioce>
		<movable-area
			:style="{
				width: windowWidth + 'px',
				height: windowHeight + 'px', // 修正拼写错误
				position: 'fixed', // 固定在窗口，不随滚动移动
				top: 0,
				left: 0,
				right: 0,
				bottom: 0,
				zIndex: 9999, // 确保在最上层
				pointerEvents: 'none' // 允许点击穿透到下层内容
			}"
		>
			<movable-view direction="all" style="pointer-events: auto" x="500" y="800">
				<RightBar v-if="rightBarShow" type="" :bottom="120 + 'rpx'"></RightBar>
			</movable-view>
		</movable-area>
	</view>
</template>

<script>

import { sendText, voiceMsg, mediaMsg, videoMsg, reSendMsg } from '../../methods/msgSend.js';
import { initMsgData } from '../../methods/initMsgData.js';
import { webScoketMsg } from '../../methods/handleWebSocketMessage.js';
import customnavbar from '@/components/customnavbar';
import recordVioce from '../../components/recordVioce.vue';
import getMsgFromStore from '../../utils/getMsgFromStore';
import previewImageWithCache from '../../utils/previewImageWithCache.js';
// import { clearUnRead } from '@/utils/chatList.js';

import formatMessageTime from '@/utils/formatMessageTime.js';
import RightBar from '../../components/RightBar.vue';
import { VoicePlayer } from '@/utils/VoicePlayer';
import * as msgAction from '@/utils/msgAction.js';
import progressBar from '../../components/progressBar.vue';
const linli = uniCloud.importObject('linliChat', { customUI: true });
import chatFromStore from '../../utils/chatFromStore';

export default {
	components: {
		customnavbar,
		progressBar,
		recordVioce,
		RightBar,
	
	},
	data() {
		return {
			keyboardHeight: 0,
			windowHeight: 0,
			isInputShow: true,
			scrollViewHeight: 0,
			scroll: 0,
			rightBarShow: true,
			windowWidth: 0,
			progressPercent: 0,
			isSpeak: false,
			targetUser: {},
			audioContext: null,
			user: {},
			messages: [],
			toTarget: {},
			lastTimes: 0,
			viewId: '',
			currentMsg: -1,
			runs: 0,
			page: 1,
			pageSize: 20
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		},
		stateConfig() {
			return this.$store.state.msg.stateConfig;
		},
		newMsg() {
			return this.$store.state.msg.newMessage || {};
		}
	},
	watch: {
		messages: {
			handler(newMsg) {
				console.log('消息体', newMsg);
				if (!Array.isArray(newMsg) || newMsg.length === 0) {
					console.warn('监听到的 messages 非有效数组', newMsg);
					return;
				}
				this.$nextTick(() => {
					const lastMsg = newMsg[newMsg.length - 1];
					if (lastMsg && lastMsg.timestamp !== undefined) {
						this.viewId = `msgall-${lastMsg.timestamp}`;
					} else {
						console.warn('最新消息格式异常，无法设置滚动目标', lastMsg);
					}
				});
			},
			deep: true,
			immediate: false
		},
		newMsg: {
			handler(newVal) {
				// 1. 基础校验：过滤无效值
				if (!newVal || newVal === null || typeof newVal !== 'object' || Object.keys(newVal).length === 0) {
					return;
				}

				// 2. 校验消息是否属于当前聊天（增加可选链，避免属性不存在报错）
				const isCurrentChat =
					// 自己发送给当前目标的消息
					(newVal.sendUserId === this.storeData.user?.userId && newVal.toTarget?.targetId === this.toTarget?.targetId) ||
					// 当前目标发送给自己的消息
					(newVal.toTarget?.targetId === this.storeData.user?.userId && newVal.sendUserId === this.toTarget?.targetId);

				if (isCurrentChat) {
					// 3. 统一处理消息状态（标记已读、已发送）
					const newMsg = { ...newVal, isRead: true, isSended: true };

					// 4. 安全更新消息数组
					if (Array.isArray(this.messages)) {
						const idx = this.messages.findIndex((item) => item?.timestamp === newMsg.timestamp);
						if (idx !== -1) {
							// 更新已有消息（避免中间变量引用错误）

							this.messages = this.messages.map((item, i) => (i === idx ? newMsg : item));
						} else {
							// 新增消息

							this.messages = [...this.messages, newMsg];
						}
					} else {
						// 兜底：初始化数组（使用处理后的 newMsg 而非原始 newVal）
						console.warn('this.messages 不是数组，初始化消息列表', this.messages);
						this.messages = [newMsg];
					}
				}
			},
			deep: true
		}
	},

	mounted() {
		this.adjustLayout();

		uni.onKeyboardHeightChange((res) => {
			this.keyboardHeight = res.height;
			if (this.keyboardHeight > 0) {
				this.rightBarShow = false;
				this.keyScroll();
			} else {
				this.rightBarShow = true;
			}
		});
		this.user = this.storeData.user;
		uni.$on('progressPercent', (res) => {
			this.progressPercent = res;
		});
		uni.$on('currentMsg', (res) => {
			this.currentMsg = res;
		});
	},
	beforeDestroy() {
		uni.$off('private_msg');
		uni.$off('progressPercent');
		uni.$off('currentMsg');
	},

	async onLoad(res) {
		console.log('进入私聊页，路由参数：', res);
       
		// 1. 强制校验路由参数 id，缺失时提示并返回
		if (!res?.id) {
			uni.showToast({
				title: '缺少聊天对象ID',
				icon: 'none',
				duration: 2000
			});
			// 延迟回退，确保用户看到提示
			setTimeout(() => uni.navigateBack(), 2000);
			return;
		}

		try {
			// 2. 完整初始化 toTarget（包含 targetType，私聊场景通常为 2，根据业务调整）
			this.toTarget = {
				targetId: res.id,
				targetType: '2' // 明确私聊的 targetType，与 MessageSender 校验匹配
			};
			console.log('私聊目标初始化完成：', this.toTarget);

			// 3. 初始化数据和用户信息（确保顺序执行）
			this.initData(res.id); // 初始化聊天记录相关
			await this.getUserInfo(res.id); // 获取用户详情，等待完成后再执行后续

			// 4. 可选：初始化完成后滚动到最新消息
			this.$nextTick(() => {
				if (this.messages.length > 0) {
					const lastMsg = this.messages[this.messages.length - 1];
					this.viewId = `msgall-${lastMsg.timestamp}`;
				}
			});
		} catch (error) {
			// 5. 捕获初始化过程中的所有错误（如 getUserInfo 失败）
			console.error('私聊页初始化失败：', error);
			uni.showToast({
				title: '加载聊天信息失败',
				icon: 'none',
				duration: 2000
			});
			setTimeout(() => uni.navigateBack(), 2000);
		}
	},
	onShow() {
		this.keyScroll();
	},
	methods: {
		initData(id) {
			this.$store.commit('msg/SET_currentChatKey', `msg_person_${id}`); //存入key，标记已读
			this.chatFromStore(id);
			console.log(this.messages);
		},
		chatFromStore(id) {
			const queryParam = { type: 'person', id: id };
			const newMsg = chatFromStore(queryParam);
			newMsg.forEach(item=>{
				if(!item.isRead){
					  msgAction.clearUnRead(item); 
				}
			})
			this.messages.push(...newMsg);
		},

		lastTimestamp(index) {
			if (index > 0) {
				return this.messages[index - 1].timestamp;
			} else {
				return 0;
			}
		},
		async keyScroll() {
			if (this.messages.length === 0) return;
			await this.$nextTick();
			const query = uni.createSelectorQuery().in(this);
			query
				.select('.scroll') // scroll-view 元素
				.boundingClientRect()
				.select('.mainbord') // 消息列表外层容器
				.boundingClientRect()
				.exec(async (res) => {
					// res[0] 是 scroll-view 的信息，res[1] 是消息容器的信息
					console.log(res);
					const scrollViewRect = res[0];
					const msgContainerRect = res[1];

					if (!scrollViewRect || !msgContainerRect) {
						console.error('未找到滚动区或消息容器');
						return;
					}

					// 3. 计算滚动到底部的距离：消息总高度 - scroll-view 高度
					const scrollToBottom = msgContainerRect.height - scrollViewRect.height;

					await this.$nextTick(); // 等待重置生效
					this.scroll = this.scroll + Math.abs(scrollToBottom);

					console.log('强制滚动到底部，距离：', scrollToBottom);
				});
		},

		//初始化存储
		formatMessageTime,
		recordVioceClose() {
			(this.isSpeak = false), (this.isInputShow = true);
		},
		hangdleInputshow() {
			this.isInputShow = false;
			this.isSpeak = true;
		},
		handonPlay(msg) {
			// 先停止当前播放
			if (this.currentMsg !== -1 && this.currentMsg !== msg.timestamp) {
				VoicePlayer.stop();
				this.onPlay = false;
				this.isPlaying = false;
			}

			// 查找当前消息在列表中的索引
			const index = this.messages.findIndex((item) => item.timestamp === msg.timestamp);

			if (index === -1) {
				console.warn('未找到对应的消息');
				return;
			}

			// 切换播放状态
			this.onPlay = !this.onPlay;

			if (!this.onPlay) {
				this.isPlaying = false;
				VoicePlayer.stop();
			} else {
				this.isPlaying = true;
				VoicePlayer.play(this, index);
			}
		},

		TouchMain() {
			uni.$emit('mainPageClickEven');
		},
		async getUserInfo(id) {
			try {
				// 1. 精准查询：只返回需要的字段，减少冗余和安全风险
				const userInfo = await linli.getUserInfo(id, { userId: true, nicName: true, nicPic: true, userTel: true });
				// 2. 用户不存在的场景：明确提示后回退
				if (!userInfo.code) {
					uni.showToast({
						title: '该用户不存在或拒绝私聊',
						icon: 'none',
						duration: 2000 // 正确设置提示时长
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 2000); // 与提示时长一致，确保用户看到提示
					return;
				}

				// 3. 用户存在：安全处理可能为undefined的字段
				const user = userInfo.data;
				this.targetUser = {
					targetId: user.userId,
					targetName: user.nicName || '匿名用户',
					// 先判断nicPic是否存在，再取url（避免undefined错误）
					nicPic: user.nicPic?.url || '', // 若没有图片，用空字符串兜底
					userTel: user.userTel || '' // 手机号可能不存在，兜底
				};

				this.toTarget = { ...this.toTarget, targetName: user.nicName, targetType: '3' };
			} catch (error) {
				// 4. 错误场景：提示“获取失败”，而非“用户拒绝”
				console.error('获取用户信息失败：', error); // 打印具体错误便于调试
				uni.showToast({
					title: '获取用户信息失败，请稍后重试',
					icon: 'none',
					duration: 3000
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 3000);
			}
		},
		loadMore() {
			console.log('页面刷新');
		},
		async reLoadmsgList(id) {
			console.warn('删除聊天记录需要重做！！！！！');
			this.messages = await getMsgFromStore(id);
		},
		sendmsg(msg) {
			this.messages.push(msg.msg);
			console.log('增加了信息了吗？', this.messages);
		},
		// async initMsgData() {
		// 	await initMsgData(this);
		// },
		async adjustLayout() {
			try {
				const res = this.storeData.systemInfo;
				this.windowHeight = res.windowHeight;
				this.windowWidth = res.windowWidth;
			} catch (error) {
				console.error('获取系统信息时出错:', error);
			}
		},
		// async sendText(msg) {
		// 	const msgtext = await sendText(this.toTarget, msg, this.storeData);
		// 	this.messages.push(msgtext);
		// },

		reSendMsg(item) {
			reSendMsg(item);
		},
		videoplay(msg) {
			const formated = encodeURIComponent(JSON.stringify(msg));
			uni.navigateTo({
				url: `/pages/videoPlay/videoPlay?msg=${formated}`
			});
		},
		isTimeshow(timestamp, lastTimestamp) {
			if (lastTimestamp > 0) {
				if (timestamp - lastTimestamp < 300000) {
					return false;
				} else if (!timestamp) {
					return false;
				} else {
					return true;
				}
			}
		},
		preview(img) {
			previewImageWithCache(img);
		}
		// async formatMsg(res) {
		// 	//将回送信息对时间进行比较，相同的标记为已发送，并进行时间排序
		// 	try {
		// 		const msgList = await webScoketMsg(this.storeData, res);
		// 		// 遍历消息列表
		// 		for (const msg of msgList) {
		// 			// 修复findIndex的箭头函数语法，添加return
		// 			const existingIndex = this.messages.findIndex((item) => item.timestamp === msg.timestamp && this.storeData.user.userId === msg.sendUserId);

		// 			if (existingIndex === -1) {
		// 				// 新增消息，保持响应式
		// 				this.messages = [...this.messages, msg].sort((a, b) => {
		// 					return a.timestamp - b.timestamp;
		// 				});
		// 			} else {
		// 				// 更新已有消息
		// 				this.messages.splice(existingIndex, 1, msg);
		// 			}
		// 		}
		// 	} catch (e) {
		// 		console.log(e);
		// 	}
		// }
	}
};
</script>

<style lang="scss" scoped>
.mainbord {
	width: 100vw;
	height: 100vh;
	background-color: #f3f3f3;
}

.userpic {
	display: flex;
	flex-direction: column;
	justify-content: end;
	width: 120rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.nicimg {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
}
.msg_time {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 30rpx;
	color: #888888;
	font-size: 24rpx;
}
.scroll {
	display: flex;
	flex-direction: column;
	position: fixed;
	background-color: #f3f3f3;
	top: 86px;
	left: 0;
	justify-content: flex-end;
	width: 750rpx;
}

.item {
	padding: 20rpx 20rpx 0 20rpx;
	align-items: flex-start;
	align-content: flex-start;
	background-color: #f3f3f3;
	color: #333;
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	justify-content: flex-start;
	.pic {
		width: 92rpx;
		height: 92rpx;
		border-radius: 15%;
		border: #e1e1e1 solid 1px;
	}

	.content {
		padding: 15rpx;
		border-radius: 4px;
		max-width: 500rpx;
		word-break: break-all;
		line-height: 45rpx;
		position: relative;
	}

	/* 收到的消息 */
	&.pull {
		.content {
			margin-left: 32rpx;
			background-color: #fff;

			&::after {
				content: '';
				display: block;
				width: 0;
				height: 0;
				border-top: 16rpx solid transparent;
				border-bottom: 16rpx solid transparent;
				border-right: 20rpx solid #fff;
				position: absolute;
				top: 30rpx;
				left: -18rpx;
			}
		}
	}

	/* 发出的消息 */
	&.push {
		/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
		flex-direction: row-reverse;

		.content {
			margin-right: 32rpx;
			background-color: #a0e959;

			&::after {
				content: '';
				display: block;
				width: 0;
				height: 0;
				border-top: 16rpx solid transparent;
				border-bottom: 16rpx solid transparent;
				border-left: 20rpx solid #a0e959;
				position: absolute;
				top: 30rpx;
				right: -18rpx;
			}
		}
	}
}

.unsend {
	display: flex;
	align-self: center;
	width: 120rpx;
	height: 30rpx;
	font-size: 28rpx;
	color: #333;

	image {
		width: 28rpx;
		height: 28rpx;
	}
}
.progress-bar {
	text-align: center;
	font-size: 25rpx;
	color: #007bff;
	height: 100%;
	padding: 0;
	overflow: hidden;
}

.progress {
	height: 100%;
	background-color: #007bff;
	height: 8rpx;
}

.userId {
	color: #969696;
	font-size: 22rpx;
	padding-left: 30rpx;
	padding-bottom: 5rpx;
}
.media {
	display: flex;
	flex-direction: column;
	margin-right: 35rpx;
	margin-left: 35rpx;
	border-radius: 4px;
	width: 300rpx;
	max-width: 150px;
	gap: 10rpx;
	position: relative;
	image {
		max-width: 100%;
		height: auto;
	}
}
.video_v {
	width: 300rpx;
	height: 200rpx;

	border-radius: 25rpx;
}

.mark-image {
	position: absolute;
	max-width: 50%;
	max-height: 50%;
	:active {
		background-color: #3e2723;
	}
}
.video-thumbnail {
	position: relative;
	width: 300rpx;
	height: 200rpx;
}

.image-container {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
